import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router' 

Vue.use(Vuex)

export default new Vuex.Store({
  state: { 
    //用户信息
    token:null,//登录信息
    tableTabsValue: '1'
    //选项卡 数据
    , tableTabs: [],
    //购物车数据
    Cart:[],
    //奶茶数据
    MilkTea:{}
  },
  getters: {
  },
  mutations: {
    //设置奶茶数据
    setMilkTea(state, milkTea) {
      state.MilkTea = milkTea;
    },
    //设置购物车数据
    setCart(state, cart) {
      state.Cart= cart;
    },
    //登录信息
    SetToken(state,payload){
      sessionStorage.setItem("token",payload)
      state.token=payload;
    },
    //用户信息
    SetUsers(state,payload){
      sessionStorage.getItem("user",JSON.stringify(payload))
      state.Users=JSON.parse(JSON.stringify(payload))
    },
    //添加选项卡
    addTab(state, menu) {
      //先判断当前选项卡 是否存在
      if (!state.tableTabs.some(v => v.name == menu.menuID)) {
        state.tableTabs.push({
          title: menu.menuName,
          name: menu.menuID + '',
          icon: menu.icon,
          viewUrl: menu.url
        });
      }
      //切换选中
      state.tableTabsValue = menu.menuID + '';

      //通过  tableTabsValue  当前选中选项卡获取 路由地址
      let viewUrl = state.tableTabs.filter(v => v.name == state.tableTabsValue)[0].viewUrl;
      //切换路由
      if (location.pathname !== viewUrl) {
        if(viewUrl.length>1){
          router.push(viewUrl); 
        }
          
          }  
   //   router.replace(viewUrl);

    }, 
    //移除选项卡
    removeTab(state, targetName) {
      let tabs = state.tableTabs;
      let activeName = state.tableTabsValue;
      //移除的选项卡是当前选中选项卡
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
        //通过  tableTabsValue  当前选中选项卡获取 路由地址
        let viewUrl = state.tableTabs.filter(v => v.name == activeName)[0].viewUrl;
        //切换路由
        if(viewUrl[0].lenth>0){
          router.push(viewUrl);
        }
      }
      state.tableTabsValue = activeName;
      //使用筛选移除
      state.tableTabs = tabs.filter(tab => tab.name !== targetName);
    }, 
    //点击选项卡切换
    clickTab(state) {
      //通过  tableTabsValue  当前选中选项卡获取 路由地址
      let viewUrl = state.tableTabs.filter(v => v.name == state.tableTabsValue)[0].viewUrl;
      //切换路由 
      if (location.pathname != viewUrl)
        router.push(viewUrl);
    }, 
    edittableTabsValue(state, value) {
      state.tableTabsValue = value;
    }
  },
  actions: {

  },
  modules: {
  }
})
